package net.yunxinyong.sign.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.*;
import net.yunxinyong.sign.mapper.EcnomicInventoryMapper;
import net.yunxinyong.sign.mapper.PhoneMapper;
import net.yunxinyong.sign.mapper.SignAdminMapper;
import net.yunxinyong.sign.mapper.StatusMapper;
import net.yunxinyong.sign.service.PhoneService;
import net.yunxinyong.sign.utils.ListUtils;
import net.yunxinyong.sign.utils.PageBean;
import net.yunxinyong.sign.vo.PhoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *@describe 企业电话相关
 *@author  ttbf
 *@date  2018/11/12
 */
@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private PhoneMapper phoneMapper;
    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Autowired
    private SignAdminMapper signAdminMapper;
    @Autowired
    private StatusMapper statusMapper;

    @Override
    public PageBean getList(Phone phone, Integer adminId,int page, int rows) {
        PhoneExample phoneExample = new PhoneExample();
        if (phone.getInvId() == null){
            throw new CECException(501,"缺少企业id参数");
        }
        PhoneExample.Criteria criteria = phoneExample.createCriteria().andInvIdEqualTo(phone.getInvId());
        SignAdmin signAdmin = signAdminMapper.selectByPrimaryKey(adminId);
        if (signAdmin == null){
            throw new CECException(501,"用户不存在");
        }
        EcnomicInventory ecnomicInventory = ecnomicInventoryMapper.selectByPrimaryKey((long) phone.getInvId());
        if (signAdmin.getRole().equals("普查员")){
            if (ecnomicInventory.getAdminId() != adminId){
                throw new CECException(501,"没有操作权限");
            }
        }
        if (signAdmin.getRole().equals("管理员")){
            if (!ecnomicInventory.getReferenceAddress02().equals(signAdminMapper.selectByPrimaryKey(adminId).getArea())){
                throw new CECException(501,"没有操作权限");
            }
        }
        if (page != 0 && rows != 0){
            PageHelper.startPage(page, rows);
        }
        List<Phone> phoneList = phoneMapper.selectByExample(phoneExample);
        List<PhoneVo> phoneVoList = Lists.newArrayList();
        //如果查出来是phoneList 非空，就进行分页
        if (!ListUtils.isEmpty(phoneList)){
            for (Phone phone1:phoneList){
                PhoneVo phoneVo = new PhoneVo();
                BeanUtils.copyProperties(phone1,phoneVo);
                if (phone1.getValueId() != null){
                    phoneVo.setValueName(statusMapper.selectByPrimaryKey(phone1.getValueId()).getStatusValue());
                }else {
                    phoneVo.setValueName("未通知");
                }
                phoneVoList.add(phoneVo);
            }
        }else if(ListUtils.isEmpty(phoneList)) {
            EcnomicInventory selectByPrimaryKey = ecnomicInventoryMapper.selectByPrimaryKey((long) phone.getInvId());
            if (selectByPrimaryKey == null){
                throw new CECException(501,"参数不正确");
            }
            //默认电话为底册中电话
            //先往数据库表中添加移动电话
            String cellPhoneNumber = selectByPrimaryKey.getCellPhoneNumber();
            if (cellPhoneNumber != null && !"".equals(cellPhoneNumber)){
                phone.setPhone(cellPhoneNumber);
                phone.setStatusId(8);
                phone.setType(0);
                phone.setCreateTime(new Date());
                phone.setUpdateTime(new Date());
                phoneMapper.insert(phone);
                PhoneVo phoneVo = new PhoneVo();
                BeanUtils.copyProperties(phone,phoneVo);
                phoneVo.setValueName("未通知");
                phoneVo.setPhone(cellPhoneNumber);
                phoneVoList.add(phoneVo);
            }
            //再往数据库表中添加固定电话
            if (selectByPrimaryKey.getFixedLineTelephone() != null && !"".equals(selectByPrimaryKey.getFixedLineTelephone())){
                StringBuffer fixLineNumer = new StringBuffer();
                String middleNumber = selectByPrimaryKey.getFixedLineTelephone();
                //长途区号
                if (selectByPrimaryKey.getAreaCode() != null && "".equals(selectByPrimaryKey.getAreaCode())){
                    fixLineNumer.append(selectByPrimaryKey.getAreaCode());
                    fixLineNumer.append("-");
                }
                fixLineNumer.append(middleNumber);
                if (selectByPrimaryKey.getUnitLeader() != null && !"".equals(selectByPrimaryKey.getUnitLeader())){
                    fixLineNumer.append("-");
                    fixLineNumer.append(selectByPrimaryKey.getUnitLeader());
                }
                phone.setPhone(fixLineNumer.toString());
                phone.setStatusId(8);
                phone.setCreateTime(new Date());
                phone.setUpdateTime(new Date());
                phone.setType(0);
                phoneMapper.insert(phone);
                PhoneVo phoneVo = new PhoneVo();
                BeanUtils.copyProperties(phone,phoneVo);
                phoneVo.setValueName("未通知");
                phoneVo.setPhone(fixLineNumer.toString());
                phoneVoList.add(phoneVo);
            }
        }
        PageBean<PhoneVo> pageBean = new PageBean<>();
        PageInfo<Phone> pageInfo = new PageInfo<>(phoneList);
        pageBean.setTotal(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setPageNumber(pageInfo.getPageNum());
        pageBean.setPageSize(pageInfo.getSize());
        pageBean.setPageDatas(phoneVoList);
        return pageBean;



    }

    @Override
    public Phone getPhone(Integer id) {
        return phoneMapper.selectByPrimaryKey(id);
    }

    @Override
    public Phone update(Phone phone, Integer adminId) {
        //判断权限是否可以操作
        if (!check(phone.getInvId(),adminId)){
            throw new CECException(501,"没有操作权限");
        }
        phone.setCreateTime(new Date());
        phone.setUpdateTime(new Date());
        int update = phoneMapper.updateByPrimaryKeySelective(phone);
        if (update <= 0){
            throw  new CECException(501,"更新失败");
        }
        return phone;
    }

    @Override
    public Phone insert(Phone phone, Integer adminId) {
        //判断权限是否可以操作
        if (!check(phone.getInvId(),adminId)){
            throw new CECException(501,"没有操作权限");
        }
        phone.setCreateTime(new Date());
        phone.setUpdateTime(new Date());
        int insertSelective = phoneMapper.insertSelective(phone);
        if (insertSelective <= 0){
            throw  new CECException(501,"添加失败");
        }
        return phone;
    }

    //判断权限是否可以操作
    private boolean check(Integer invId,Integer adminId){
        EcnomicInventory ecnomicInventory = ecnomicInventoryMapper.selectByPrimaryKey((long) invId);
        if (ecnomicInventory == null){
            throw new CECException(501,"企业信息有误");
        }
        SignAdmin signAdmin = signAdminMapper.selectByPrimaryKey(adminId);
        if (signAdmin.getRole().equals("管理员")){
            return ecnomicInventory.getReferenceAddress02().equals(signAdmin.getArea());
        }
        if (signAdmin.getRole().equals("root")){
            return true;
        }
        return ecnomicInventory.getAdminId().equals(adminId);
    }
}
